<template>
  <div class="groupbuy-detail-page" v-if="details.length">
    <!-- SKU Selector -->
    <el-select
      v-model="selectedIndex"
      placeholder="选择商品"
      class="sku-selector"
    >
      <el-option
        v-for="(item, i) in details"
        :key="item.skuId"
        :label="item.spuTitle"
        :value="i"
      />
    </el-select>

    <el-card shadow="hover" class="activity-card">
      <template #header>
        <h2 class="activity-title">{{ details[selectedIndex].activityName }}</h2>
        <p class="activity-time">
          活动时间：{{ format(details[selectedIndex].startTime) }}
          - {{ format(details[selectedIndex].endTime) }}
        </p>
        <p class="activity-status">
          状态：{{ statusMap[details[selectedIndex].status] }}
        </p>
      </template>

      <el-row :gutter="24" class="product-info">
        <el-col :span="8">
          <el-image
            :src="details[selectedIndex].skuImage"
            fit="cover"
            class="product-image"
            :preview-src-list="[details[selectedIndex].skuImage]"
          />
        </el-col>
        <el-col :span="16" class="product-desc">
          <h3 class="spu-title">{{ details[selectedIndex].spuTitle }}</h3>
          <p>原价：<del>¥{{ details[selectedIndex].originalPrice }}</del></p>
          <p class="group-price">
            团购价：<span>¥{{ details[selectedIndex].groupPrice }}</span>
          </p>
          <p>成团人数：{{ details[selectedIndex].requiredCount }} 人</p>
          <p>有效时长：{{ details[selectedIndex].durationMinutes }} 分钟</p>
          <p>库存：{{ details[selectedIndex].stock }}</p>
          <el-input-number
            v-model="quantity"
            :min="1"
            :max="details[selectedIndex].stock"
            size="medium"
          />
          <div class="action-buttons">
            <el-button
              type="primary"
              size="medium"
              @click="handleOpenGroup"
            >我要开团</el-button>
            <el-button
              type="primary"
              size="medium"
              @click="handleJoinPrompt"
            >我要参团</el-button>
          </div>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { detailByActivity, openGroup, joinGroupByCode } from '@/api/groupbuy'
import { useUserInfoStore } from '@/stores/userInfo'

const route         = useRoute()
const router        = useRouter()
const promotionId   = route.params.promotionId
const userStore     = useUserInfoStore()

const details       = ref([])    // all SKUs under this activity
const selectedIndex = ref(0)     // which SKU is selected
const quantity      = ref(1)
const statusMap     = { 0: '停用', 1: '启用' }
const format        = v => new Date(v).toLocaleString()

async function fetchDetail() {
  try {
    // 1. 拿到 Axios response.data
    const wrapper = (await detailByActivity(promotionId)).data
    // wrapper = { code, data, message }
    if (wrapper.code === '0' || wrapper.code === '200') {
      // 2. 真正的数据在 wrapper.data
      const payload = wrapper.data
      // 3. payload 可能是一条对象或数组，统一转成数组
      details.value = Array.isArray(payload) ? payload : [payload]
      selectedIndex.value = 0
    } else {
      ElMessage.error(wrapper.message || '获取详情失败')
    }
  } catch (e) {
    console.error(e)
    ElMessage.error('网络错误')
  }
}

onMounted(fetchDetail)


/** 支付跳转，保持不变 */
function goPay({ orderSn, groupId, inviteCode }) {
  const q = { orderSn }
  if (groupId)    q.groupId    = groupId
  if (inviteCode) q.inviteCode = inviteCode
  router.push({ path: '/pay/choose', query: q })
}

/** —— 开团 —— */
async function handleOpenGroup() {
  if (!userStore.userInfo.id) {
    ElMessage.info('请先登录')
    return router.push('/login')
  }

  const skuId = details.value[selectedIndex.value].skuId

  try {
    // 1. 调用接口
    const wrapper = (await openGroup({ skuId, quantity: quantity.value })).data
    // 2. 处理返回
    if (wrapper.code === '0' || wrapper.code === '200') {
      const { orderSn, groupId, inviteCode } = wrapper.data
      ElMessageBox.confirm(
        `邀请码：<b>${inviteCode}</b>`,
        '开团成功',
        {
          dangerouslyUseHTMLString: true,
          type: 'info',
          confirmButtonText: '去支付',
          cancelButtonText: '查看拼团详情'
        }
      )
      .then(() => {
        // 用户点“去支付”
        goPay({ orderSn, groupId, inviteCode })
      })
      .catch(() => {
        // 用户点“查看拼团详情”或关闭弹窗
        router.push({ name: 'GroupDetail', params: { groupId } })
      })
    } else {
      ElMessage.error(wrapper.message || '开团失败')
    }
  } catch (err) {
    console.error(err)
    ElMessage.error('网络错误，请稍后重试')
  }
}

/** —— 参团 —— */
async function handleJoinPrompt() {
  if (!userStore.userInfo.id) {
    ElMessage.info('请先登录')
    return router.push('/login')
  }

  try {
    const { value: code } = await ElMessageBox.prompt(
      '请输入好友提供的邀请码',
      '参团',
      {
        inputPlaceholder: '邀请码',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }
    )
    if (!code) return

    const skuId = details.value[selectedIndex.value].skuId
    const wrapper = (await joinGroupByCode({
      inviteCode: code.trim(),
      quantity:   quantity.value
    })).data

    if (wrapper.code === '0' || wrapper.code === '200') {
      const { orderSn, groupId } = wrapper.data
      ElMessage.success('下单成功，正在跳转支付')
      goPay({ orderSn, groupId })
    } else {
      ElMessage.error(wrapper.message || '参团失败')
    }
  } catch (err) {
    if (err !== 'cancel') {
      console.error(err)
      ElMessage.error('网络错误，请稍后重试')
    }
    // 用户取消无需处理
  }
}

</script>

<style scoped>
.groupbuy-detail-page {
  max-width: 960px;
  margin: 30px auto;
  padding: 20px;
  background: #f5f7fa;
}
.sku-selector {
  display: block;
  width: 300px;
  margin: 0 auto 20px;
}
.activity-card {
  border-radius: 14px;
}
.activity-title {
  font-size: 22px;
  font-weight: 600;
  color: #303133;
}
.activity-time, .activity-status {
  font-size: 14px;
  color: #909399;
  margin-top: 4px;
}
.product-info {
  margin-top: 20px;
}
.product-image {
  width: 100%;
  height: 220px;
  border-radius: 12px;
  object-fit: cover;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}
.product-desc {
  display: flex;
  flex-direction: column;
  gap: 10px;
  justify-content: center;
}
.spu-title {
  font-size: 20px;
  font-weight: 500;
  margin-bottom: 10px;
}
.group-price {
  font-size: 18px;
  color: #f56c6c;
}
.group-price span {
  font-size: 20px;
  font-weight: bold;
}
.el-button[type="primary"] {
  width: 140px;
  border-radius: 20px;
}
.action-buttons {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 20px;
}
</style>
